package com.example.agent_springai.contoller;

import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblWidth;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTblWidth;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.net.URL;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

@RestController
@RequestMapping("/api")
public class WordGenerateController {

    @PostMapping("/generate-word")
    public ResponseEntity<byte[]> generateWord(@RequestBody WordGenerateRequest request) throws Exception {
        XWPFDocument doc = new XWPFDocument();

        // 标题排版
        XWPFParagraph titlePara = doc.createParagraph();
        titlePara.setAlignment(ParagraphAlignment.CENTER);
        XWPFRun titleRun = titlePara.createRun();
        titleRun.setText("故障诊断报告");
        titleRun.setFontSize(20);
        titleRun.setBold(true);
        titleRun.setFontFamily("微软雅黑");
        titlePara.setSpacingAfter(400);

        // 正文与表格智能排版
        String content = request.getTextContent();
        if (content != null && !content.isEmpty()) {
            String[] lines = content.split("\n");
            List<String> paraBuffer = new ArrayList<>();
            XWPFTable table = null;
            boolean isInTable = false;

            for (String line : lines) {
                line = line.trim();
                if (line.isEmpty()) {
                    if (!paraBuffer.isEmpty()) {
                        createNormalParagraph(doc, paraBuffer);
                        paraBuffer.clear();
                    }
                    continue;
                }

                if (line.startsWith("|") && line.contains("|") && line.split("\\|").length > 2) {
                    if (!paraBuffer.isEmpty()) {
                        createNormalParagraph(doc, paraBuffer);
                        paraBuffer.clear();
                    }

                    if (!isInTable) {
                        table = doc.createTable();
                        table.setWidth("100%");
                        CTTblWidth tblWidth = table.getCTTbl().addNewTblPr().addNewTblW();
                        tblWidth.setType(STTblWidth.PCT);
                        tblWidth.setW(BigInteger.valueOf(1000));
                        isInTable = true;
                    }

                    String[] cells = line.split("\\|");
                    XWPFTableRow tableRow = table.getRow(table.getNumberOfRows() - 1);

                    if (table.getNumberOfRows() == 1) {
                        for (int i = 1; i < cells.length - 1; i++) {
                            tableRow.addNewTableCell();
                        }
                    } else {
                        while (tableRow.getTableCells().size() < table.getRow(0).getTableCells().size()) {
                            tableRow.addNewTableCell();
                        }
                    }

                    for (int i = 1; i < cells.length - 1; i++) {
                        String cellText = cells[i].trim();
                        if (i - 1 < tableRow.getTableCells().size()) {
                            XWPFTableCell cell = tableRow.getCell(i - 1);
                            cell.setText(cellText);
                            XWPFParagraph cellPara = cell.getParagraphs().get(0);
                            cellPara.setAlignment(ParagraphAlignment.CENTER);

                            if (table.getNumberOfRows() == 1 || line.contains("-----")) {
                                cell.setColor("DDEBF7");
                                XWPFRun cellRun = cellPara.getRuns().get(0);
                                cellRun.setBold(true);
                            }
                        }
                    }

                    if (isInTable) {
                        table.createRow();
                    }

                } else {
                    paraBuffer.add(line);
                }
            }

            if (!paraBuffer.isEmpty()) {
                createNormalParagraph(doc, paraBuffer);
            }

            if (table != null) {
                XWPFParagraph tableAfterPara = doc.createParagraph();
                tableAfterPara.setSpacingBefore(200);
            }
        }

        // ====================== 图表排版（支持Base64和URL图片） ======================
        if (request.getChartBase64() != null && !request.getChartBase64().isEmpty()) {
            XWPFParagraph chartTitlePara = doc.createParagraph();
            chartTitlePara.setAlignment(ParagraphAlignment.CENTER);
            XWPFRun chartTitleRun = chartTitlePara.createRun();
            chartTitleRun.setText("温度趋势图"); // 可根据实际图表类型动态修改标题
            chartTitleRun.setFontSize(14);
            chartTitleRun.setBold(true);
            chartTitleRun.setFontFamily("微软雅黑");
            chartTitlePara.setSpacingAfter(200);

            XWPFParagraph chartPara = doc.createParagraph();
            chartPara.setAlignment(ParagraphAlignment.CENTER);
            XWPFRun chartRun = chartPara.createRun();

            byte[] imageBytes;
            // 区分“Base64图片”和“阿里系图片URL”
            if (request.getChartBase64().startsWith("data:image/")) {
                // 处理Base64图片
                String base64WithoutPrefix = request.getChartBase64().split(",")[1];
                imageBytes = Base64.getDecoder().decode(base64WithoutPrefix);
            } else {
                // 处理阿里系图片URL（自动下载）
                URL imageUrl = new URL(request.getChartBase64());
                InputStream imageStream = imageUrl.openStream();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int len;
                while ((len = imageStream.read(buffer)) != -1) {
                    baos.write(buffer, 0, len);
                }
                imageStream.close();
                imageBytes = baos.toByteArray();
            }

            // 插入图片到Word（自动识别格式，若为PNG则用PICTURE_TYPE_PNG，JPG则用PICTURE_TYPE_JPEG）
            String imageType = String.valueOf(request.getChartBase64().contains(".png") ? XWPFDocument.PICTURE_TYPE_PNG : XWPFDocument.PICTURE_TYPE_JPEG);
            InputStream imageStream = new ByteArrayInputStream(imageBytes);
            chartRun.addPicture(
                    imageStream,
                    Integer.parseInt(imageType),
                    "chart.png",
                    Units.toEMU(450), // 加宽图片宽度，提升展示效果
                    Units.toEMU(280)  // 加高图片高度
            );
            imageStream.close();
            chartPara.setSpacingAfter(400);
        }

        // 写入并返回Word
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        doc.write(out);
        doc.close();

        String fileName = "故障诊断报告.docx";
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8");

        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.wordprocessingml.document"))
                .header("Content-Disposition", "attachment; filename=\"" + encodedFileName + "\"")
                .body(out.toByteArray());
    }

    // 工具方法：创建普通段落
    private void createNormalParagraph(XWPFDocument doc, List<String> contentLines) {
        XWPFParagraph para = doc.createParagraph();
        para.setAlignment(ParagraphAlignment.LEFT);
        para.setIndentationFirstLine(Units.toEMU(36)); // 首行缩进2字符
        para.setSpacingBefore(100);
        para.setSpacingAfter(200);
        para.setSpacingAfterLines(160); // 行间距设为24磅（更易读）

        XWPFRun run = para.createRun();
        run.setText(String.join(" ", contentLines));
        run.setFontSize(12);
        run.setFontFamily("微软雅黑"); // 正文统一用微软雅黑，提升现代感
        run.setColor("333333"); // 深灰色文字，减轻视觉疲劳
    }

    // 接收前端数据的请求类
    static class WordGenerateRequest {
        private String textContent;
        private String chartBase64;

        public String getTextContent() { return textContent; }
        public void setTextContent(String textContent) { this.textContent = textContent; }
        public String getChartBase64() { return chartBase64; }
        public void setChartBase64(String chartBase64) { this.chartBase64 = chartBase64; }
    }
}